return JsonResponse(

{'error':'unable to login. check username and password'},

status=400)

If no user is found, we return a JsonResponse object with a dictionary containing an error message and status code

of 400 indicating that the request cannot be fulfilled.

Analyze Code

else: # return user token

try:

token = Token.objects.get(user=user)

except: # if token not in db, create a new one

token = Token.objects.create(user=user)

return JsonResponse({'token':str(token)}, status=201)

Else, it means that the authentication is successful and we found a user. We then retrieve an existing user token with

Token.objects.get(user=user) or create a new one if the token is not in the database.

Testing Our App

Let’s now test our login endpoint. In Insomnia, send a POST request to the login URL

http://localhost:8000/api/login/ with the JSON object containing username and password (fig. 1).

Figure 1

After sending the request, the response should return an authorization token. With it, you can then run in the

Terminal:

Execute in Terminal

curl http://localhost:8000/api/todos/ -H 'Authorization:Token <token>'

to retrieve todos.

You can also use cURL to complete todos e.g.

Execute in Terminal

curl -X "PUT" http://localhost:8000/api/todos/2/complete -H 'Authorization:Token <token>'

Now that we have implemented and tested our backend API endpoints, let’s proceed on to implement the React

frontend in the next chapter!

REACT FRONTEND